package com.pan.behavioral.stratergy.game;

import com.pan.behavioral.stratergy.pattern.Strategy;
import com.pan.behavioral.stratergy.pattern.StrategyContext;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


/**
 *
 *
 */
@Deprecated
public class ClickGame implements StrategyContext {
    JFrame frame;

    JFrame tipsFrame;
    JLabel tipsLabel;
    JButton ballButton;

    JFrame switchFrame;
    public ClickGame(){

        frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setSize(400,400);
        frame.setLayout(null);
        tipsFrame = new JFrame();
        tipsFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        tipsLabel = new JLabel("失败");

        ballButton = new JButton();
        ballButton.setSize(20,20);
        ballButton.addActionListener(new ActionListener() {
            private int count=0;
            @Override
            public void actionPerformed(ActionEvent e) {
                if (count>=10){
                    tipsLabel.setText("成功");
                    ballButton.setVisible(false);
                    flag =false;
                }else {
                    count++;
                    ballButton.setVisible(false);
                }
            }
        });
        frame.add(ballButton);

        switchFrame = new JFrame();
        switchFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        switchFrame.setSize(200,100);

        JButton switchButton = new JButton();
        switchButton.setText("random");
        switchButton.setBounds(50,30,100,40);
        switchButton.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {
                createStrategy("random");
                run();
                switchFrame.setVisible(false);
                switchFrame.dispose();
            }
        });
        switchFrame.add(switchButton);
    }

    public void start(){
        switchFrame.setVisible(true);
    }
    private boolean flag = true;
    public void run(){
        frame.setVisible(true);

        while (flag){
            strategy.operation(0);
            ballButton.setVisible(true);
            frame.repaint();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        tipsFrame.add(tipsLabel);
        tipsFrame.pack();
        tipsFrame.setVisible(true);

    }
    public void createStrategy(String name) {
        if (name.equals("random")) {
            this.setStrategy(new RandomStrategy(frame.getWidth(),frame.getHeight(),ballButton));
        }
    }

    private Strategy strategy;

    @Override
    public void setStrategy(Strategy strategy) {
        this.strategy = strategy;
    }
}
